from message import SendMessage
import pymongo


def Mongodb(ColName, data, mongo_host, mongo_database,robot_url, consul_host):
    # 连接Mongo
    client = pymongo.MongoClient(mongo_host)
    db = client[mongo_database]
    col = db[ColName]
    key_mongo, key_data = [], []
    for x in col.find({}, {'_id': 0, 'KEY': 1}):
        key_mongo.append(x['KEY'])
    for d in data:
        query = {'KEY': d['KEY']}
        result = col.find_one(query, {'_id': 0, 'KEY': 1, 'VALUE': 1})
        if result:
            if result['VALUE'] != d['VALUE']:
                info = {'Type': '修改KEY', 'Name': d['KEY'], 'Output': "Update Key", 'Status': 'Updated'}
                newValue = {'$set': d}
                col.update_one(query, newValue)
                SendMessage(info, robot_url, consul_host)
        else:
            info = {'Type': '新增KEY', 'Name': d['KEY'], 'Output': "Add New Key", 'Status': 'Added'}
            col.insert_one(d)
            SendMessage(info, robot_url, consul_host)
        key_data.append(d['KEY'])
    old_key = list(set(key_mongo) - set(key_data))
    if old_key:
        for key in old_key:
            info = {'Type': '删除KEY', 'Name': key, 'Output': "Delete Key", 'Status': 'Deleted'}
            value = col.find_one({'KEY': key}, {'_id': 0})
            col.delete_one(value)
            SendMessage(info, robot_url, consul_host)